// 头部组件
import "./header.scss"
import { getCookie, setCookie } from "@u/cookie_utils"

const data = [
    { text: "小米商城", url: '//www.mi.com/index.html' },
    { text: 'MIUI', url: '//www.miui.com/' },
    { text: 'IoT', url: '//iot.mi.com' },
    { text: '云服务', url: '//i.mi.com/' },
    { text: '天星数科', url: '//airstar.com/home' },
    { text: '有品', url: '//youpin.mi.com/' },
    { text: '小爱开发平台', url: '//xiaoai.mi.com/' },
    { text: '企业团购', url: '//qiye.mi.com/' },
    { text: '资质证照', url: '//www.mi.com/aptitude/list/?id=88' },
    { text: '协议规则', url: '//www.mi.com/aptitude/list/' },
    { text: '下载app', url: '//www.mi.com/appdownload/', src: "//i1.mifile.cn/f/i/17/appdownload/download.png?1" },
    { text: '智能生活', url: '//xiaomishare.mi.com/?from=micom' },
    { text: 'Select Location', url: 'javascript:void(0)' },
    { text: '登录', url: './login.html' },
    { text: '注销', url: '#' },
    { text: '消息通知', url: 'javascript:void(0)' },
    { text: '购物车', url: '//www.mi.com/buy/cart', icon: "iconfont icon-gouwuche" },

]

export default (() => {

    let header = document.createElement("header")
    let nav = document.createElement("div")
    nav.classList.add("nav", "auto")
    let leftNav = document.createElement("div")
    let rightNav = document.createElement("div")
    leftNav.classList.add("left-nav")
    rightNav.classList.add("right-nav")

    data.forEach((item, index) => {
        const { text, url } = item
        if (index < data.length - 4) {
            text === '下载app'
                ? leftNav.innerHTML += `<a href="${url}">${text}<span id="appcode"><img src="${item.src}"></img>小米商城App</span></a><span class="sep">|</span>`
                : leftNav.innerHTML += `<a href="${url}">${text}</a>${index < data.length - 5 ? '<span class="sep">|</span>' : ''}`

        } else {
            text === '购物车'
                ? rightNav.innerHTML += `<a href="${url}" class="cart"><i class="iconfont icon-gouwuche"></i><span>${text}</span><span>(0)</span><div class="cart-menu"><div class="loader"></div><span>购物车还没有商品!</span></div></a>`
                : rightNav.innerHTML += `<a href="${url}">${text === '登录' ? '欢迎你 ' + JSON.parse(localStorage.getItem("token")).name : text}</a>${index < data.length - 2 ? '<span class="sep">|</span>' : ''}`
        }
    });

    [...rightNav.querySelectorAll("a")]
        .filter(a => a.innerText === '注销')[0].addEventListener("click", e => {
            e.preventDefault()
            setCookie("token", null, -1)
            window.location.href = './login.html'
        })
    nav.appendChild(leftNav)
    nav.appendChild(rightNav)
    header.appendChild(nav)


    app.appendChild(header)

    return header
})()
